import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { showConfirmDialog } from 'vant'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      meta: {
        showTabbar: true,
      },
    },
    {
      path: '/cate',
      name: 'cate',
      component: () => import('../views/CateView.vue'),
      meta: {
        showTabbar: true,
      },
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('../views/CartView.vue'),
      meta: {
        // showTabbar: true,
        requireLogin: true,
      },
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login/LoginView.vue'),
    },
    {
      path: '/my',
      name: 'my',
      component: () => import('../views/MyView.vue'),
      meta: {
        showTabbar: true,
        requireLogin: true,
      },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/login/Register.vue'),
    },
    {
      path: '/modify',
      name: 'modify',
      component: () => import('../views/login/Modify.vue'),
    },
    {
      path: '/detail',
      name: 'detail',
      meta: { keepAlive: false },
      component: () => import('../views/DetailView.vue'),
    },
    {
      path: '/position',
      name: 'position',
      meta: { keepAlive: false, showTabbar: true, requireLogin: true },
      component: () => import('../views/Position.vue'),
    },
    {
      path: '/AddAddress',
      name: 'AddAddress',
      meta: { keepAlive: false, showTabbar: true, requireLogin: true },
      component: () => import('../views/AddAddress.vue'),
    },
    {
      path: '/EditAddress',
      name: 'EditAddress',
      meta: { keepAlive: false, showTabbar: true, requireLogin: true },
      component: () => import('../views/EditAddress.vue'),
    },
    {
      path: '/search',
      name: 'search',
      redirect: { name: 'index' },
      children: [
        {
          path: '/',
          name: 'index',
          component: () => import('../views/search/SearchIndex.vue'),
        },
        {
          path: 'list',
          name: 'list',
          component: () => import('../views/search/SearchList.vue'),
        },
      ],
      component: () => import('../views/SearchView.vue'),
    },
  ],
})

router.beforeEach((to) => {
  if (to.meta.requireLogin === true) {
    let saveUserInfo = localStorage.getItem('saveUserInfo')
    if (saveUserInfo == null) {
      showConfirmDialog({
        title: '提示',
        message: '当前用户暂未登录，是否需要登录？',
      })
        .then(() => {
          router.push('/login')
        })
        .catch(() => {})
      return false
    }
  }
})

export default router
